package net.zjitc.servlet;

import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import net.zjitc.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/9/29.
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        UserService loginService=new UserServiceImpl();
        User user= null;
        try {
            user = loginService.findAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(user.getPassword().equals(password)&&user.getUsername().equals(username))
        {
            HttpSession session=request.getSession();
            session.setAttribute("user",user);
            Cookie cookie=new Cookie("username",user.getUsername());
            cookie.setMaxAge(60*24*24);
            response.addCookie(cookie);
            response.sendRedirect("/Web/success.jsp");
        }
        else {
            request.setAttribute("msg","您输入的用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
